'use strict';
const fiip = require('fiip');
const stdp = require('fiip-protocol-stdp');
const linkUdp = require('fiip-link-udp');
const path = require('path');
const fs = require('fs');

const connectCloud = async function() {
  const dns = require('dns');
  const hostname = '0.fiip.fengdid.cn';
  const ip = await dns.promises.resolve(hostname);
  const link = new fiip.Link.Client();
  link.type = fiip.Link.type.udp;
  link.address = ip[0];
  link.port = 16464;
  fiip.connect(fiip.centerId, link);
  console.log('cloud is:%s,%d.', link.address, link.port);
};

module.exports = (agent) => {
  agent.beforeStart(async () => {
    const { id, port } = agent.config.fiip;

    fiip.init();
    fiip.setId(id);
    linkUdp.start('0.0.0.0', port);

    connectCloud();

    stdp.start();
    const listenersPath = path.join(agent.baseDir, 'app/fiip/listeners');
    fs.readdirSync(listenersPath).forEach((file) => {
      const fun = agent.loader.loadFile(path.join(listenersPath, file));
      stdp.addListener(parseInt(fun.name.substr(8, 6)), fun);
    });

    fiip.__proto__.txd = new stdp.Format();
    fiip.__proto__.clients = {}; // 以id为key的设备列表
    fiip.__proto__.vars = {}; // 以id为key的云端变量列表
    fiip.__proto__.binding = {}; // 设备绑定模式
    agent.fiip = fiip;
  });
};
